package com.cgnpc.scp.achievement.controller;

import com.cgnpc.cud.annotation.OperatorType;
import com.cgnpc.cud.annotation.UBA;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.achievement.mybatis.entity.Standard;
import com.cgnpc.scp.achievement.mybatis.entity.Subject;
import com.cgnpc.scp.achievement.pojo.IdReq;
import com.cgnpc.scp.achievement.pojo.SaveSubjectReq;
import com.cgnpc.scp.achievement.pojo.SubjectDetail;
import com.cgnpc.scp.achievement.service.SubjectService;
import com.cgnpc.scp.common.bean.CreateFileInfo;
import com.cgnpc.scp.common.bean.MyPageResult;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.utils.AjaxResultUtil;
import com.cgnpc.scp.common.utils.FileUtil;
import com.cgnpc.scp.common.utils.XSSFilterUtils;
import com.cgnpc.scp.purchase.mybatis.entity.PurchaseProject;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Locale;

@Controller
@RequestMapping("/scp/achievement/subject")
public class SubjectController
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SubjectController.class);

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private MessageSource messageSource;

    @Autowired
    private CurrentUser currentUser;
    /**********************************
     * 用途说明: 保存科研课题
     * 参数说明 SaveSubjectReq
     * 返回值说明:
     ***********************************/
    @ApiOperation(value="保存科研课题")
    @UBA(module = "成果管理", action = "保存科研课题", channel = OperatorType.Button)
    @RequestMapping(value = "/save", method = {RequestMethod.POST})
    @ResponseBody
    public AjaxResult save(HttpServletRequest request, @RequestBody SaveSubjectReq saveReq) {
        Subject subject = subjectService.saveSubject(saveReq);

        if (subject != null)
            return AjaxResultUtil.createI18nDefaultSuccess(request,messageSource,subject);
        else
            return AjaxResultUtil.createI18nDefaultError(request,messageSource,"保存失败!");
    }


    /**********************************
     * 用途说明: 查询科研课题 列表
     * 参数说明 subject
     * 返回值说明:
     ***********************************/
    @ApiOperation(value="查询科研课题 列表")
    @UBA(module = "成果管理", action = "查询科研课题 列表", channel = OperatorType.Button)
    @RequestMapping(value = "/listPage", method = {RequestMethod.POST})
    @ResponseBody
    public AjaxResult listPage(HttpServletRequest request, @RequestBody Subject subject) {
        MyPageResult<Subject> result = subjectService.querySubjectPageList(subject);
        return AjaxResultUtil.createI18nDefaultSuccess(request,messageSource,result);
    }


    /**********************************
     * 用途说明: 根据ID 查询科研课题 详细信息
     * 参数说明 id
     * 返回值说明:
     ***********************************/
    @ApiOperation(value="根据ID 查询科研课题 详细信息")
    @UBA(module = "成果管理", action = "查询科研课题 详细信息", channel = OperatorType.Button)
    @RequestMapping(value = "/getInfoById", method = {RequestMethod.POST})
    @ResponseBody
    public AjaxResult getInfoById(HttpServletRequest request, @RequestBody IdReq req) {
        SubjectDetail result = subjectService.querySubjectDetailById(req.getId());
        if (result != null)
            return AjaxResultUtil.createI18nDefaultSuccess(request,messageSource,result);
        else
            return AjaxResultUtil.createI18nDefaultError(request,messageSource,"查询失败，没有找到对应记录!");
    }

    /**********************************
     * 用途说明: 删除科研课题
     * 参数说明
     * 返回值说明:
     ***********************************/
    @ApiOperation(value="删除科研课题")
    @UBA(module = "成果管理", action = "删除科研课题", channel = OperatorType.Button)
    @RequestMapping(value = "/delByIds", method = {RequestMethod.POST})
    @ResponseBody
    public AjaxResult delByIds(HttpServletRequest request, @RequestBody List<String> ids) {
        if (subjectService.delByIds(ids))
            return AjaxResultUtil.createI18nDefaultSuccess(request,messageSource);
        else
            return AjaxResultUtil.createI18nDefaultError(request,messageSource,"删除失败!");
    }


    /**********************************
     * 用途说明: 删除科研课题
     * 参数说明
     * 返回值说明:
     ***********************************/
    @ApiOperation(value="删除科研课题")
    @UBA(module = "成果管理", action = "删除科研课题", channel = OperatorType.Button)
    @RequestMapping(value = "/downLoadFiles", method = {RequestMethod.POST})
    public void downLoadFiles(HttpServletResponse response, @RequestBody IdReq req) throws Exception {
        boolean allow = subjectService.isAllowDownload(req.getId());
        if (allow) {
            File file = subjectService.genDownLoadFiles(req.getId());
            file = FileUtil.formatSafeFileWithDownloadFile(file);

            String filename=file.getName();
            filename= XSSFilterUtils.cleanXSS(file.getName());
            if (file != null) {
                response.reset();
                response.setContentType("bin");
                response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

                InputStream inStream = null;
                try {
                    inStream = new FileInputStream(file);
                    byte[] b = new byte[1024];
                    int len;
                    while ((len = inStream.read(b)) > 0)
                        response.getOutputStream().write(b, 0, len);
                    response.flushBuffer();
                } catch (Exception e) {
                    LOGGER.error(e.getMessage());
                } finally {
                    try {
                        if (inStream != null) inStream.close();
                        FileUtil.delete(file);
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage());
                    }
                }
            }
        }
    }

    /**********************************
     * 用途说明: 调试科研创新管理===成果管理===能力建设====导出Excel
     * 参数说明: HttpServletRequest request, @RequestBody T reqEntity
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "调试科研创新管理-成果管理-科研课题--导出Excel")
    @UBA(module = "调试科研创新管理", action = "科研课题导出 Excel", channel = OperatorType.Button)
    @RequestMapping(value = "/exportExcel", method = {RequestMethod.POST})
    @ResponseBody
    public <T extends Subject> Object exportExcel(HttpServletRequest request, @RequestBody T reqEntity) {
        AjaxResult ajaxResult = null;

        try {
            CreateFileInfo createFileInfo = subjectService.exportExcel(reqEntity);
            ajaxResult = AjaxResultUtil.createSuccessMessage(createFileInfo);
        } catch (Exception e) {
            LOGGER.error("exportExcel.error;", e);
            ajaxResult = AjaxResultUtil.createErrorMessage();
        }

        return ajaxResult;
    }

    /**********************************
     * 用途说明: 调试科研创新管理-成果管理-科研课题---导入Excel
     * 参数说明: HttpServletRequest request
     * 返回值说明: Object
     ***********************************/
    @ApiOperation(value = "调试科研创新管理-成果管理-科研课题---导入Excel")
    @UBA(module = "调试科研创新管理", action = "科研课题导入 Excel", channel = OperatorType.Button)
    @RequestMapping(value = "/importFromExcel", method = {RequestMethod.POST})
    @ResponseBody
    public <T extends Subject> Object importFromExcel(MultipartHttpServletRequest request) {
        AjaxResult ajaxResult = null;

        try {
            // 获取当前的登录用户信息
            UserInfo loginUserInfo = currentUser.getCurrentUserDetail();
            // 获取请求的语言reqLocale，cookie需要包含lang=cn，或者lang=en
            Locale reqLocale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);

            MultipartFile reqFile = request.getFile("file");

            ajaxResult = subjectService.importFromExcel(loginUserInfo, reqLocale, reqFile);
        } catch (Exception e) {
            LOGGER.error("importFromExcel.error;", e);
            ajaxResult = AjaxResultUtil.createErrorMessage();
        }

        return ajaxResult;
    }

}
